"use strict";

const tma = require("tt-ide-cli"); // 官方文档：https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/developer-instrument/development-assistance/ide-cli
const Service = require("egg").Service;

class DouyinService extends Service {
  constructor(ctx) {
    super(ctx);

    this.parmas = ctx.request.body;

    const root = this.parmas.root || "../packages/miniprogram";
    const appid = this.parmas.appid;

    this.changeLog = this.parmas.desc;
    this.version = this.parmas.version;

    this.projectPath = `${root}/mp-toutiao`;
    this.qrcodeOutputDest = `${root}/${appid}_preview.jpg`;
    this.sourceMapSavePath = `${root}/${appid}_sourceMap.zip`;

    tma.setAppConfig({ appid, config: { token: this.parmas.private } });

    this.project = {
      path: this.projectPath, // 项目地址
    };

    this.qrcodeCOnfig = {
      format: "imageSVG",
      output: "",
      options: { small: false },
    };

    process.on("uncaughtException", function (err) {
      // 打印出错误
      console.log(err);
      // 打印出错误的调用栈方便调试
      console.log(err.stack);
    });
  }

  async end() {
    await tma.logout();
  }

  async upload() {
    return await tma.upload({
      project: this.project,
      qrcode: this.qrcodeCOnfig,
      copyToClipboard: true, // 是否将产出的二维码链接复制到剪切板
      changeLog: this.changeLog,
      version: this.parmas.version,
      needUploadSourcemap: true,
    });
  }

  async preview() {
    const res = await this._preview();
    res.base64 = await this._readfile(this.qrcodeOutputDest);
    return res;
  }

  async sourceMap() {
    await this._getDevSourceMap();
    return await this._readMap(this.sourceMapSavePath);
  }
}

module.exports = DouyinService;
